import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_app_info.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/common/xindong_storage.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_yinsi_singleton.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/routes/account/controller/xindong_register_ctr.dart';
import 'package:xindong/routes/account/xindong_password_login_yemian.dart';
import 'package:xindong/routes/account/xindong_register_yemian.dart';
import 'package:xindong/widgets/dialog/xindong_alert_message.dart';
import 'package:xindong/widgets/xindong_countdown_button.dart';

class XinDongLoginCtr extends GetxController {
  static XinDongLoginCtr get to => Get.find();

  final _registerController = Get.put(XinDongRegisterCtr());
  final FocusNode codeFocusNode = FocusNode();
  late TextEditingController codeController;
  late TextEditingController phoneController;

  RxBool enableLoginButton = false.obs;

  // 配置
  // 重置数据，避免下次使用同样的数据
  void setup() {
    XinDongRegisterCtr.to.setup();
    // 读取保存的手机号码
    String savePhone = XinDongStorage.instance.getString(XinDongStorageKey.phone) ?? "";
    phoneController = TextEditingController(text: savePhone);
    // 光标保持在最后
    phoneController.selection = TextSelection.fromPosition(TextPosition(offset: phoneController.text.length));
    phoneController.addListener(() {
      validationEnableLogin();
    });
    // 清空验证码
    codeController = TextEditingController(text: "");
    codeController.addListener(() {
      validationEnableLogin();
    });
    // 校验能否登录
    validationEnableLogin();
  }

  // 校验能否登录
  void validationEnableLogin() {
    final phone = phoneController.text;
    final code = codeController.text;
    enableLoginButton.value = false;
    if (phone.length >= 5 && code.length >= 4) {
      enableLoginButton.value = true;
    }
    // update();
  }

  // 监听自动登录
  void onAutoLogin() {
    if (enableLoginButton.value) {
      requestLogin();
    }
  }

  // 获取验证码事件
  void onGetCode() async {
    if (XinDongYinSiSingleton.to.checkAllPrivacyAgree() == false) {
      return;
    }
    showLoading();
    final phone = phoneController.text;
    var parameters = {"phone": phone, "device_id": XinDongAppDeviceInfo.instance.deviceUDID};
    final object = await XinDongNetworking.instance.request(
      XinDongApi.codeGet,
      method: XinDongHttpMethod.post,
      parameters: parameters,
      addUserId: false,
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      codeFocusNode.requestFocus();
      XinDongCountdownButtonCtr.to.start();
    } else if (object.code == XinDongServerStatus.codeReuse) {
      // 使用上次验证码
      codeFocusNode.requestFocus();
    }
  }

  void requestLogin() async {
    if (XinDongYinSiSingleton.to.checkAllPrivacyAgree() == false) {
      return;
    }
    validationEnableLogin();
    if (!enableLoginButton.value) {
      return;
    }

    showLoading();
    final phone = phoneController.text;
    final code = codeController.text;
    var parameters = {
      "phone": phone,
      "code": code,
      "prefix": "86",
      "oaid": XinDongAppDeviceInfo.instance.deviceOAID,
      "device_id": XinDongAppDeviceInfo.instance.deviceUDID,
    };
    final object = await XinDongNetworking.instance.request(
      XinDongApi.codeLogin,
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      // 登录成功
      XinDongUserController.to.commonLoginSuccessfulHandler(
        userId: "${object.result["id"]}",
        sig: "${object.result["tencentId"]}",
        gender: object.result["sex"],
      );
      // 保存登录手机号
      XinDongStorage.instance.saveString(XinDongStorageKey.phone, phone);
    }
    // 未注册，要去完善资料
    else if (object.code == XinDongServerStatus.unregistered) {
      _registerController.registerClass.phone = phone;
      _registerController.registerClass.code = code;
      toRegisterYeMian(phone);
    }
    // 已注销，要去完善资料
    else if (object.code == XinDongServerStatus.zhuXiao) {
      XinDongAlertMessage.show(
        content: object.msg,
        onTapButton: () {
          _registerController.registerClass.phone = phone;
          _registerController.registerClass.code = code;
          toRegisterYeMian(phone);
        },
      );
    }
  }

  void requestLoginWithPassword({required String account, required String password}) async {
    if (XinDongYinSiSingleton.to.checkAllPrivacyAgree() == false) {
      return;
    }

    showLoading();
    var parameters = {
      "phone": account,
      "password": password,
      "oaid": XinDongAppDeviceInfo.instance.deviceOAID,
      "device_id": XinDongAppDeviceInfo.instance.deviceUDID,
    };
    final object = await XinDongNetworking.instance.request(
      XinDongApi.passwordLogin,
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      // 登录成功
      XinDongUserController.to.commonLoginSuccessfulHandler(
        userId: "${object.result["id"]}",
        sig: "${object.result["tencentId"]}",
        gender: object.result["sex"],
      );
    }
  }

  void toPasswordLoginYeMian() async {
    if (XinDongYinSiSingleton.to.checkAllPrivacyAgree() == false) {
      return;
    }
    XinDongPageSingleton.instance.pushYeMian(const XinDongPasswordLoginYeMian());
  }

  void toRegisterYeMian(String phone) {
    FocusScope.of(currentContext()).requestFocus(FocusNode());
    XinDongPageSingleton.instance.pushYeMian(const XinDongRegisterYeMian());
    // 保存登录手机号
    XinDongStorage.instance.saveString(XinDongStorageKey.phone, phone);
  }
}
